<template>
  <div class="system-customer">
    <Modal
      :mask-closable="false"
      v-model="form.show"
      title="表单历史版本"
      width="70%"
      :transfer="false"
    >
      <div>

        <el-form ref="form" :model="form" style="display: block">
          <el-form-item label="版本" prop="versionData">
            <el-checkbox-group v-model="form.checkdData">
              <el-checkbox :key="item.id" :label="item.id" v-for="(item,index) in form.versionData">{{item.version}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>

      </div>
      <div slot="footer">
        <Button @click="handleReset('informed')">取消</Button>
        <Button type="primary" @click="informedHandler">确定</Button>
      </div>
    </Modal>
    <xr-header/>

    <div class="customer-content">
      <div class="system-view-nav">
        <Tree :data="categoryData" expand="true" default-expand-all="true" @on-select-change="refreshTask"/>

      </div>

      <div class="system-view-content" >
        <div class="option-bar">
          <el-row type="flex" justify="start" style="margin-left: -25px">

            <el-form :inline="true" :model="queryForm" class="demo-form-inline" size='mini' style="margin-left: -3%">


              <el-form-item label="类型">
                <el-select v-model="queryForm.formType" placeholder="请选择" clearable>
                  <el-option
                    v-for="item in formTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>

              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="queryForm.status" placeholder="请选择" clearable>
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>

              </el-form-item>
              <el-form-item label="名称">
                <el-input v-model="queryForm.name" clearable></el-input>
              </el-form-item>
              <el-form-item label="别名">
                <el-input v-model="queryForm.formKey" clearable></el-input>
              </el-form-item>
              <el-form-item style="margin-left: 56px">
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="default" @click="reset">重置</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </div>
        <el-row style="margin-top: 10px">
          <el-col>
            <el-table
              :data="tableData"
              size="mini"
              style="width: 100%"
              :height="tableHeight"
              @row-click="handleRowClick"
              @selection-change="handleSelectionChange"

            >
              <el-table-column
                type="selection"
                fixed
                width="55">
              </el-table-column>
              <el-table-column
                label="序号"
                type="index"
                width="50"
                fixed
                align="center">
                <template slot-scope="scope">
                  <span>{{(queryForm.page-1 ) * queryForm.pageSize + scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="名称"
                show-overflow-tooltip
              />
              <el-table-column
                prop="formKey"
                label="别名"
                show-overflow-tooltip
              />
              <el-table-column
                prop="formType"
                label="类型"
                show-overflow-tooltip
              />
              <el-table-column
                prop="status"
                label="状态"
                show-overflow-tooltip
              >
                <template slot-scope="scope">


                  <el-tag type="success" v-if="(scope.row.status==='deploy') "> 发布</el-tag>
                  <el-tag type="warning" v-else> 草稿</el-tag>

                </template>


              </el-table-column>
              <el-table-column
                prop="groupName"
                label="分组"
                show-overflow-tooltip
              />
              <el-table-column
                prop="version"
                label="版本号"
                show-overflow-tooltip
              />

              <el-table-column
                fixed="right"
                label="操作"
                width="250">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleRowClick()">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <div class="p-contianer">
          <el-pagination
            background
            class="p-bar"
            :current-page="queryForm.page"
            :page-size="queryForm.pageSize"
            layout="prev, pager, next, sizes, total, jumper"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <Modal
      :mask-closable="false"
      v-model="show"
      title="预览"
      width="70%"
      :transfer="false"
    >

      <div v-if="jsonData.config!=null" class="container"    style=" overflow: auto;max-height: 550px">

        <fm-generate-form
          ref="generateForm"
          :data="jsonData"
          :remote="remoteFuncs"
          :value="editData"
          :remote-option="dynamicData"
          :builtMap="built"
        />


      </div>
      <div slot="footer">
        <el-button type="primary" @click="previewData()" >
          数据预览
        </el-button>
        <el-button @click="show=false">取消</el-button>

      </div>

    </Modal>
    <Modal
      :mask-closable="false"
      v-model="showJson"
      title="预览"
      width="70%"
      :transfer="false"
    >

      <div>
        <vue-json-editor
          v-model="json"
          :show-btns="true"
          :mode="'code'"
          lang="zh"
        >

        </vue-json-editor>
      </div>

      <div slot="footer">

      </div>

    </Modal>
  </div>

</template>
<style rel="stylesheet/scss" lang="scss" scoped>
  .p-contianer {
    position: relative;
    background-color: white;
    height: 44px;
    .p-bar {
      float: right;
      margin: 5px 100px 0 0;
      font-size: 14px !important;
    }
  }
  .option-bar {
    padding: 15px 20px;
  }
  .system-customer {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    padding: 0 15px;
  }
  .customer-content {
    flex: 1;
    position: relative;
    display: flex;
    overflow: hidden;
  }
  .system-view-nav {
    min-width: 200px;
    background: #fff;
    margin-right: 10px;
    padding-top: 20px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;

  }
  .system-view-content {
    flex: 1;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    background: #fff;
    display: flex;
    flex-direction: column;
    overflow-x: auto;
  }

  // 菜单
  .menu-item {
    color: #333;
    font-size: 13px;
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    cursor: pointer;
    position: relative;
    .icon-close {
      position: absolute;
      top: 0;
      right: 8px;
      z-index: 1;
      display: none;
    }
  }

  .menu-item:hover,
  .menu-item.is-select {
    background-color:  #F6F8FA;
  }

  .menu-item:hover::before,
  .menu-item.is-select::before {
    content: ' ';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 2px;
    background-color: #5383ed;
  }
</style>

<script>
  import vueJsonEditor from 'vue-json-editor'

  import { download } from '@/api/analy'
  import {
    getTypesByKey,
    synchronizationForm,
    getFormModelTableListJson,
    updateFormModel,
    getFormModelVersion,
    delDesignByCodesEs,
    delDesignByCodes
  } from '@/api/form'
  import XrHeader from '@/components/XrHeader'

  export default {
    name: 'Task',
    components: {
      vueJsonEditor,
      XrHeader
    },

    data() {
      return {
        json: {
        }
        ,
        jsonData: {},
        built: {},
        editData: {},
        remoteFuncs: {},
        dynamicData: {},
        showJson: false,
        show: false,
        multiple: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        formTypeOptions: [{
          value: 'pc',
          label: 'pc'
        }, {
          value: 'mobile',
          label: '移动端'
        }],
        statusOptions: [{
          value: 'draft',
          label: '草稿'
        }, {
          value: 'deploy',
          label: '发布'
        }],
        form: {
          show: false,
          formKey: "",
          isIndeterminate: true,
          checkAll: false,
          versionData: [],
          checkdData: []
        },
        tableData: [],
        ids: [],
        modelerSrc: '',
        tableHeight: 450,
        queryDate: [],
        total: 0,
        chartVisible: false,
        chartData: {},
        sellerId: 0,
        shopName: [],
        queryForm: {
          groupId: '',
          formType: '',
          formKey: '',
          name: '',
          status: '',
          page: 1,
          pageSize: 10,
          limit: 10
        },
        multipleSelection: [],
        categoryData: []
      }
    },
    mount() {
      this.getData()
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
    },
    created() {
      this.initData()
    },

    methods: {
      /**
       * 当某一行被点击时会触发该事件
       */
      handleRowClick(row, column, event) {
        this.$router.push({
          name: 'crmPrintDetail',
          query: {
            handle: 'detail',
            templateName: row.name,
            formKey: row.formKey,
            templateId: row.id,
          }
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.ids = val.map(item => item.formKey)
        this.single = val.length !== 1
        this.multiple = !val.length
      },
      synchronization() {
        synchronizationForm(this.multipleSelection).then((response) => {
          download(response, '表单模型')
        })
      },
      handleReset: function () {
        this.form.checkdData = []
        this.form.show = false
      },

      informedHandler: function () {
        updateFormModel({ids: this.form.checkdData, formKey: this.form.formKey}).then((response) => {
          if (response.code == 0) {
            this.$message({"duration": '800', message: '操作成功', type: 'success', customClass: 'zZindex'});
            this.handleReset();
          }
        })


      },
      handleCheckAllChange(val) {
        // this.form.versionData = val ? this.form.versionData  : [];
        // this.form.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        // let checkedCount = value.length;
        // this.form.checkAll = checkedCount === this.form.versionData.length;
        // this.form.isIndeterminate = checkedCount > 0 && checkedCount < this.form.versionData.length;
      },
      add: function () {
        this.$router.push({name: 'formModelerIndex', query: {t: new Date().getTime(), 'operate': 'inner'}})


      },
      queryFormCreateTime: function (e) {
        this.queryForm.createTime = e
      },
      refreshTask: function (data) {
        this.queryForm.page = 1
        if (data[0].parentId == '-1') {
          this.queryForm.groupId = ''
        } else {
          this.queryForm.groupId = data[0].id
        }
        this.queryForm.page = 1

        this.getData()
      },
      queryMethod: function () {
        this.getData();
      },
      getTypesByKeyAction: function () {
        getTypesByKey().then((response) => {
          this.categoryData = response.data
        })
      },
      initData: function () {
        this.getTypesByKeyAction();
        this.getData();
      },
      getData: function () {

        getFormModelTableListJson(this.queryForm).then((response) => {
          this.tableData = response.data
          this.total = parseInt(response.count)
        })
      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.getData()
      },
      handleClick(data) {
        this.$router.push({
          name: 'crmPrintDetail',
          query: {
            handle: 'detail',
            templateName: row.templateName,
            templateId: row.templateId,
            type: row.type
          }
        })
      },
      handleVersionClick(data) {
        this.$router.push({name: 'formVersionManager', query: {t: new Date().getTime(), 'modelKey': data.formKey}})

      },
      previewData(){
        if (this.$refs.generateForm) {
          this.$refs.generateForm.getData().then(data => {
            this.json=data
            this.showJson=true


          })
        }
      },
      handleCommand(command) {
        switch (command.flag) {
          case 'handleVersionClick':
            this.handleVersionClick(command.row)
            break
          case 'updateClick':
            this.updateClick(command.row)
            break
          case 'handleDelClick':
            this.handleDelClick(command.row)
            break
          case 'preview':
            this.preview(command.row)
            break
        }
      },
      preview(data){
        this.editData={}
        this.jsonData=JSON.parse(data.pageFormJsonStr)
        if (this.$refs.generateForm){
          this.$refs.generateForm.reset()
        }

        this.show=true
      },
      handleDelete(){
        delDesignByCodes(this.ids.join(",")).then((response) => {
          if (response.code == 0) {
            this.getData()
          } else {
            this.$message({"duration": '800', message: response.msg, type: 'warning', customClass: 'zZindex'});

          }
        })
      },
      handleEs(){
        delDesignByCodesEs(this.ids.join(",")).then((response) => {
          if (response.code == 0) {
            this.$message({"duration": 800, message: '同步成功', type: 'success', customClass: 'zZindex'});

          } else {
            this.$message({"duration": '800', message: response.msg, type: 'warning', customClass: 'zZindex'});

          }
        })
      },
      handleDelClick(row) {
        const ids = row.id || this.ids;
        var formKeys = row.formKey ;
        this.$confirm('是否确认删除表单模型编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delDesignByCodes(formKeys);
        }).then((res) => {
          if (res.code==0){
            this.getData();
            this.msgSuccess("删除成功");
          }else{
            this.$message({"duration": '800', message: res.msg, type: 'warning', customClass: 'zZindex'});

          }

        })

      },
      updateClick(data) {
        var formKey = data.formKey

        this.form.formKey = formKey
        getFormModelVersion(formKey).then((response) => {
          if (response.code == 0) {
            this.form.versionData = response.data

          }
        })

        this.form.show = true;


      },
      search() {
        this.queryForm.page = 1
        this.queryMethod()
      },
      reset() {
        this.queryForm.name = ''
        this.queryForm.createTime = ''
        this.queryForm.formKey = ''
        this.queryForm.formType = ''
        this.queryForm.status = ''
        this.queryDate = []
        this.getData()
      }

    }

  }

</script>
<style lang="scss" scoped>
  .task-card {
    margin-top: 10px;
  }

</style>
<style lang="scss" scoped>
  .container {
    overflow:auto;
    min-height: 450px;
  }
  /* button color */
  .el-button--cyan.is-active,
  .el-button--cyan:active {
    background: #20B2AA;
    border-color: #20B2AA;
    color: #FFFFFF;
  }

  .el-button--cyan:focus,
  .el-button--cyan:hover {
    background: #48D1CC;
    border-color: #48D1CC;
    color: #FFFFFF;
  }

  .el-button--cyan {
    background-color: #20B2AA;
    border-color: #20B2AA;
    color: #FFFFFF;
  }

  /* text color */
  .text-navy {
    color: #1ab394;
  }

  .text-primary {
    color: inherit;
  }

  .text-success {
    color: #1c84c6;
  }

  .text-info {
    color: #23c6c8;
  }

  .text-warning {
    color: #f8ac59;
  }

  .text-danger {
    color: #ed5565;
  }

  .text-muted {
    color: #888888;
  }

  /* image */
  .img-circle {
    border-radius: 50%;
  }

  .img-lg {
    width: 120px;
    height: 120px;
  }

  .avatar-upload-preview {
    position: absolute;
    top: 50%;
    transform: translate(50%, -50%);
    width: 200px;
    height: 200px;
    border-radius: 50%;
    box-shadow: 0 0 4px #ccc;
    overflow: hidden;
  }

  /* 拖拽列样式 */
  .sortable-ghost {
    opacity: .8;
    color: #fff !important;
    background: #42b983 !important;
  }

  .top-right-btn {
    position: relative;
    float: right;
  }

  .main-div {
    background-color: white !important;
  }

</style>
